<?php

class SearchForm extends CFormModel
{
	public $credit_id;
	public $surname;
	public $name;
	public $patronymic;
	public $series;
	public $number;

	public $no_data;

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules()
	{
		return array(
			array('credit_id', 'numerical', 'integerOnly'=>true),
			array('no_data','checkEmpty'),
			array('surname,name,patronymic,series,number','safe')
		);
	}

	public function checkEmpty()
	{
		if(!$this->surname and !$this->name and !$this->patronymic and !$this->credit_id and !$this->series and !$this->number){
			$this->addError('no_data','Данные для поиска не введены.');
		}
	}

	public function beforeValidate()
	{
		parent::beforeValidate();
		array_map('trim',$this->attributes);
		return true;
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'credit_id'  => 'Номер договора',
			'surname'	 => 'Фамилия',
			'name'		 => 'Имя',
			'patronymic' => 'Отчество',
			'series'	 => 'Серия',
			'number'	 => 'Номер'
		);
	}

	public function searchClient()
	{
		$criteria = new CDbCriteria;

		$criteria->with = array('passports');
		$criteria->together = true;

		$criteria->compare('surname',$this->surname);
		$criteria->compare('name',$this->name);
		$criteria->compare('patronymic',$this->patronymic);
		$criteria->compare('CONCAT(passports.series,passports.number)',$this->series.''.$this->number);

		return new CActiveDataProvider('Clients', array(
			'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>100,
			),
		));
	}

	public function searchCredit()
	{
		$criteria = new CDbCriteria;
		$criteria->with = 'shops';

		$criteria->compare('t.id',$this->credit_id);

		if(Yii::app()->user->getState('role') != Users::ADMIN_ROLE)
			$criteria->compare('shops.organization_id',Yii::app()->user->getState('organization_id'));

		return new CActiveDataProvider('Credits', array(
			'criteria'=>$criteria
		));
	}
}